# coding = utf-8

import subprocess, os, time, json, sys

p, i = 0, 0


def runTask(**kwargs):
    global p, i
    t = time.time()
    if 'rule' not in kwargs:
        kwargs['rule'] = "bxwx"
    if 'mode' not in kwargs:
        kwargs['mode'] = "new100"
    if p != 0:
        p.stdout.close()
    print("[LOG]Task Started : %s %s in mode %s" % (kwargs['rule'], kwargs['key'], kwargs['mode']))
    p = subprocess.Popen("cd %s && " % os.getcwd() + "python3 mintrss.py %s %s %s" % (
        kwargs['rule'], '"' + kwargs['key'] + '"', kwargs['mode']), shell=True, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE)
    for line in iter(p.stdout.readline, 'b'):
        line = line.rstrip().decode('utf8')
        print(line[:5] + "[Task %s]" % sys.argv[i] + line[5:])
        if subprocess.Popen.poll(p) is not None:
            if line == "":
                break
    p.wait()
    print("[LOG]Task completed,this task's time consumption is %ds" % (time.time() - t))
    return p.returncode


if __name__ == '__main__':
    t = time.time()
    if len(sys.argv) == 1:
        sys.argv.append("TASKS")
    for i in range(1, len(sys.argv)):
        print("[LOG]LoadTaskList %d:%s" % (i, sys.argv[i]))
        try:
            t = time.time()
            fh = open(sys.argv[i], 'r', encoding='utf-8')
            tasks = json.loads(fh.read())
            fh.close()
            result = [runTask(**task) for task in tasks]
        except BaseException as e:
            print("[ERROR]" + str(e))
            continue
        else:
            print("[LOG]Task list time consumption is %ds" % (time.time() - t))
    print("[LOG]Total time consumption is %ds" % (time.time() - t))
